'use strict';

var contentPath;
var translateMap = {};
var translateLoaded = false;
var lang = 'zh';
var splitWords = '#@#';
var menu = [];
var page = {};
var pageHolder = {};
var pageIndex = 0;

(function () {
    var pathName = window.location.pathname.substring(1);
    var webName = pathName === '' ? '' : pathName.substring(0, pathName.indexOf('/'));
    contentPath = window.location.protocol + '//' + window.location.host + (webName === 'schedule' || webName === '' ? '' : ('/' + webName));
})();

function loadTranslateMap(url, func) {
    if (translateLoaded === true) {
        func && func();
        return;
    }
    if (url && url !== '') {
        var index = url.indexOf(',');
        if (index === -1) {
            $.getJSON(contentPath + url, function (data) {
                translateMap[url.substring(url.indexOf('_') + 1, url.indexOf('.'))] = data;
                translateLoaded = true;
                func && func();
            });
        } else if (index === 0) {
            loadTranslateMap(url.substr(1), func);
        } else {
            var currUrl = url.substr(0, index);
            $.getJSON(contentPath + currUrl, function (data) {
                translateMap[currUrl.substring(currUrl.indexOf('_') + 1, currUrl.indexOf('.'))] = data;
                loadTranslateMap(url.substr(index + 1), func);
            });
        }
    }
}

function loadMenu(url, func) {
    $.getJSON(contentPath + url, function (data) {
        menu = data;
        func && func();
    });
}

function getParentMenuItem(name) {
    return getMenuChildItem(menu, name, true);
}

function getMenuChildItem(items, name, isParentItem, nameArray) {
    for (var i in items) {
        if (items.hasOwnProperty(i)) {
            if (items[i]['name'] === name) {
                return items[i];
            }
            var childs = items[i]['childs'];
            if (childs !== null) {
                var menuItem = getMenuChildItem(childs, name, isParentItem, nameArray);
                if (menuItem !== null) {
                    nameArray && nameArray.push(menuItem.name);
                    return isParentItem ? items[i] : menuItem;
                }
            }
        }
    }
    return null;
}

function getMenuItem(parentMenuItem, name) {
    if (parentMenuItem['name'] === name) {
        return parentMenuItem;
    }
    var childs = parentMenuItem['childs'];
    if (childs !== null) {
        var menuItem = getMenuChildItem(childs, name, false);
        if (menuItem !== null) {
            return menuItem;
        }
    }
    return parentMenuItem;
}

function getMenuNameArray(parentMenuItem, name) {
    var nameArray = [];
    if (parentMenuItem['name'] === name) {
        nameArray.push(name);
    } else {
        var childs = parentMenuItem['childs'];
        if (childs !== null) {
            var menuItem = getMenuChildItem(childs, name, true, nameArray);
            if (menuItem !== null) {
                nameArray.push(menuItem.name);
            }
            nameArray.push(parentMenuItem.name);
        } else {
            nameArray.push(name);
        }
    }
    return nameArray;
}

function refreshDataTables() {
    var dataTables = $('table.dataTable');
    if (dataTables && dataTables.length > 0) {
        var oldPage = page.dataTable.page();
        var searchValue = page.dataTable.search();
        var pageLength = page.dataTable.page.len();
        page.dataTable.destroy();
        translate(dataTables);
        createSearchTableBody(dataTables.find('tbody'));
        page.dataTable.search(searchValue).page(oldPage).page.len(pageLength).draw(false);
        textEllipsis();
        dataTableNiceScroll();
    }
}

function translate(node) {
    var translateNodes = node.hasClass('translate') ? node : node.find('.translate');
    if (translateNodes) {
        $.each(translateNodes, function (i, translateNode) {
            var $translateNode = $(translateNode);
            if ($translateNode.attr('translateFor')) {
                if ($translateNode.attr('translateTo')) {
                    $translateNode.attr($translateNode.attr('translateTo'), getTranslateValue($translateNode));
                } else {
                    $translateNode.text(getTranslateValue($translateNode));
                }
            }
            if ($translateNode.hasClass('lang')) {
                $translateNode.removeClass('en zh').addClass(lang);
            }
        });
    }
    return node;
}

function getTranslateValue($translateNode) {
    var translateFor = $translateNode.attr('translateFor') || '';
    var translateValue = getTranslateValueByFor(translateFor);
    if (translateValue === undefined || translateValue === '') {
        return '';
    }
    $translateNode.attr('translateValue') && (translateValue = translateValue[$translateNode.attr('translateValue')]);
    var translateReplace = $translateNode.attr('translateReplace');
    if (translateReplace && translateReplace !== '' && translateReplace !== 'undefined') {
        while (translateValue.indexOf('{}') > -1 && translateReplace !== '') {
            var commaIndex = translateReplace.indexOf(';');
            var replaceTarget;
            if (commaIndex > 0) {
                replaceTarget = translateReplace.substring(0, commaIndex);
                translateReplace = translateReplace.substring(commaIndex + 1);
            } else {
                replaceTarget = translateReplace;
                translateReplace = '';
            }
            var replaceValue;
            var cdataStartIndex = replaceTarget.indexOf('cdata(');
            if (cdataStartIndex !== -1) {
                replaceValue = replaceTarget.substring(cdataStartIndex + 6, replaceTarget.indexOf(')'));
            } else {
                var pointIndex = replaceTarget.indexOf('.');
                if (pointIndex > 0) {
                    replaceValue = translateMap[lang][replaceTarget.substring(0, pointIndex)][replaceTarget.substring(pointIndex + 1)];
                } else {
                    replaceValue = translateMap[lang][replaceTarget];
                }
            }
            translateValue = translateValue.replace('{}', replaceValue);
        }
    }
    return translateValue;
}

function cdata(str) {
    return 'cdata(' + str + ")";
}

function getTranslateReplace(array) {
    if (array === undefined || array === null) {
        return "";
    }
    if (!(array instanceof Array)) {
        return array;
    }
    var str = "";
    for (var i in array) {
        if (array.hasOwnProperty(i)) {
            str += array[i] + ";";
        }
    }
    if (str !== "") {
        return str.substr(0, str.length - 1);
    }
    return str;
}

function getTranslateFor($translateNode) {
    var translateFor = $translateNode.attr('translateFor') || '';
    var translateValue = $translateNode.attr('translateValue') || '';
    if (translateFor === '' && translateValue === '') {
        return '';
    } else if (translateFor === '' && translateValue !== '') {
        return translateValue;
    } else if (translateFor !== '' && translateValue === '') {
        return translateFor;
    }
    return translateFor + '.' + translateValue;
}

function getTranslateValueByFor(translateFor) {
    if (translateFor === '') {
        return '';
    }
    var pointIndex = translateFor.indexOf('.');
    var translateValue = translateMap[lang];
    while (pointIndex > -1) {
        translateValue = translateValue[translateFor.substring(0, pointIndex)];
        translateFor = translateFor.substring(pointIndex + 1);
        pointIndex = translateFor.indexOf('.');
    }
    return translateValue[translateFor];
}

function setLang(_lang) {
    lang = _lang;
}

function getLang() {
    return lang;
}

function changeLang(langSwitchBtn1, langSwitchBtn2, lang1, lang2) {
    langSwitchBtn1.addClass('switch-loading');
    langSwitchBtn2.addClass('switch-loading');
    lang = langSwitchBtn1.hasClass('switch-checked') ? lang2 : lang1;
    axiosPost({
        url: "/schedule/setting/changeLang/" + lang,
        success: function (json) {
            if (lang === lang2) {
                langSwitchBtn1.removeClass('switch-checked');
                langSwitchBtn2.addClass('switch-checked');
            } else {
                langSwitchBtn1.addClass('switch-checked');
                langSwitchBtn2.removeClass('switch-checked');
            }
            translate($('body'));
            refreshDataTables();
            langSwitchBtn1.removeClass('switch-loading');
            langSwitchBtn2.removeClass('switch-loading');
        }
    });
}

function showPopover(node, options) {
    var id = options.id || 'default';
    var popoverTimeoutId = node.data('popoverTimeoutId_' + id);
    if (popoverTimeoutId !== undefined && popoverTimeoutId !== '') {
        clearTimeout(popoverTimeoutId);
        node.data('popoverTimeoutId_' + id, '');
    }
    var popover;
    var popoverId = node.data('popoverId_' + id);
    if (popoverId && popoverId !== '') {
        popover = $('#' + popoverId);
    } else {
        popover = createPopover(options).data('node', node).data('firstShow', true);
        popoverId = popover.data('popoverId');
        node.data('popoverId_' + id, popoverId);
        var popoverIdMap = node.data('popoverIdMap');
        if (popoverIdMap === undefined) {
            popoverIdMap = {};
            node.data('popoverIdMap', popoverIdMap);
        }
        var popoverIdArray = popoverIdMap[id];
        if (popoverIdArray === undefined) {
            popoverIdArray = [];
            popoverIdMap[id] = popoverIdArray;
        } else if (popoverIdArray.length > 0) {
            for (var i in popoverIdArray) {
                if (popoverIdArray.hasOwnProperty(i)) {
                    if (popoverIdArray[i] && popoverIdArray[i] !== '') {
                        hidePopover($('#' + popoverIdArray[i]), true);
                    }
                }
            }
        }
        popoverIdArray.pushWhenNotExist(popoverId);
    }
    setPopoverData(popover, options);
    popover.css('transform', 'translate3d(-1000px, -1000px, 0px)').show().data('show', true);
    adjustPopoverPosition(popover, true);
    var sepLayerId = popover.data('sepLayerId');
    if (sepLayerId && sepLayerId !== '') {
        var seplayer = $('#' + sepLayerId);
        seplayer.addClass('z-index-9998').off('click').on('click', function () {
            hidePopover(popover)
        });
        popover.addClass('z-index-9999');
        node.addClass('z-index-9999');
        options.zIndex && node.css('z-index', 9999 + options.zIndex) && seplayer.css('z-index', 9998 + options.zIndex);
        var fixedTop = $('.fixed-top');
        if (fixedTop && fixedTop.length > 0) {
            fixedTop.each(function () {
                var $this = $(this);
                var fixedTopCover = $this.find('.cover');
                if (fixedTopCover === undefined || fixedTopCover.length === 0) {
                    fixedTopCover = $('<div class="cover"></div>');
                    $this.prepend(fixedTopCover.addClass('z-index-9999'));
                }
                fixedTopCover.off('click').on('click', function () {
                    hidePopover(popover)
                }).show();
            });
        }
    } else {
        $('#content').on('click.' + popoverId, function (event) {
            if (event.target === node[0]) {
                return;
            }
            hidePopover(popover);
            $('#content').off('click.' + popoverId)
        });
    }
    options.zIndex && popover.css('z-index', 9999 + options.zIndex);
    return popover;
}

function createPopover(options) {
    var popoverId = generateID('popover');
    var bodyStyle = options.bodyStyle || '';
    var bodyContent = options.bodyContent || '';
    var popover = $('<div id="' + popoverId + '" class="popover" style="position:absolute;will-change:transform;"></div>');
    var popoverBody = $('<div class="popover-body" style="' + bodyStyle + '"></div>');
    var body = $('body').append(popover.append($('<div class="arrow"></div>')).append(popoverBody.html(bodyContent)));
    options.niceScroll && popoverBody.niceScroll({
        cursorcolor: "rgba(52, 40, 104, 0.2)",
        cursorborder: "rgba(52, 40, 104, 0.2)"
    });
    if (options.scrollLock === true) {
        var sepLayerId = generateID('sepLayer');
        var sepLayer = $('<div class="separation-layer" id="' + sepLayerId + '"></div>');
        body.append(sepLayer);
        popover.data('sepLayerId', sepLayerId).data('scrollLock', options.scrollLock);
    }
    options.topFun && popover.data('topFun', options.topFun);
    options.bottomFun && popover.data('bottomFun', options.bottomFun);
    options.rightFun && popover.data('rightFun', options.rightFun);
    options.leftFun && popover.data('leftFun', options.leftFun);
    options.preHideFun && popover.data('preHideFun', options.preHideFun);
    options.hideFun && popover.data('hideFun', options.hideFun);
    popover.data('popoverId', popoverId);
    return popover;
}

function setPopoverData(popover, options) {
    if (options.allowBodyChange === true && options.bodyContent !== undefined && popover.data('bodyContent') !== options.bodyContent) {
        getPopoverBody(popover).html(options.bodyContent);
    }
    return popover.data('id', options.id || 'default').data('direction', options.direction || 'top').data('bodyStyle', options.bodyStyle || '').data('bodyContent', options.bodyContent || '')
        .data('popoverLeft', options.left).data('popoverTop', options.top).data('leftOffset', options.leftOffset).data('topOffset', options.topOffset)
        .data('animate', options.animate || 'no').data('animateTime', options.animateTime || 500).data('hideRemove', options.hideRemove);
}

function getPopoverId(node, id) {
    return node.data('popoverId_' + (id || 'default'));
}

function getPopoverBody(popover) {
    return popover.find('.popover-body');
}

function adjustAllPopoverPositionByNode(node) {
    var popoverIdMap = node.data('popoverIdMap');
    if (popoverIdMap !== undefined) {
        for (var key in popoverIdMap) {
            if (popoverIdMap.hasOwnProperty(key)) {
                adjustPopoverPositionByNode(node, key);
            }
        }
    }
}

function adjustPopoverPositionByNode(node, id) {
    var popoverIdMap = node.data('popoverIdMap');
    if (popoverIdMap !== undefined) {
        id = id || 'default';
        var popoverIdArray = popoverIdMap[id];
        if (popoverIdArray && popoverIdArray.length > 0) {
            var oPopoverId = node.data('popoverId_' + id);
            for (var i in popoverIdArray) {
                if (popoverIdArray.hasOwnProperty(i)) {
                    var popoverId = popoverIdArray[i];
                    if (popoverId && popoverId !== '') {
                        if (popoverId === oPopoverId) {
                            adjustPopoverPosition($('#' + popoverId));
                        } else {
                            hidePopover($('#' + popoverId), true);
                        }
                    }
                }
            }
        }
    }
}

function adjustPosition() {
    $('.popover').each(function () {
        var $this = $(this);
        if ($this.data('show') === true) {
            adjustPopoverPosition($this);
            var popoverTop = $this.offset().top;
            popoverTop !== 0 && (popoverTop + 2 < $("#content").offset().top || popoverTop + $this[0].offsetHeight - 2 > $(window).height()) && $this.css('transform', 'translate3d(-1000px, -1000px, 0px)');
        }
    });
}

function adjustPopoverPosition(popover, init, _direction, turn) {
    if (popover === undefined || popover === null || popover.data('show') !== true) {
        return;
    }
    var direction = _direction || popover.data('direction'), node = popover.data('node'), left, top;
    popover.removeClass('bs-popover-top bs-popover-bottom bs-popover-right bs-popover-left').addClass('bs-popover-' + direction).attr('x-placement', direction);
    var popoverOffsetHeight = popover.data('popoverOffsetHeight') ? popover.data('popoverOffsetHeight') : popover[0].offsetHeight;
    var popoverOffsetWidth = popover.data('popoverOffsetWidth') ? popover.data('popoverOffsetWidth') : popover[0].offsetWidth;
    var popoverClientHeight = popover.data('popoverClientHeight') ? popover.data('popoverClientHeight') : popover[0].clientHeight;
    var popoverClientWidth = popover.data('popoverClientWidth') ? popover.data('popoverClientWidth') : popover[0].clientWidth;
    var directionFun;
    if (direction === 'top') {
        popover.find('.arrow').css('left', (popoverClientWidth - 14) / 2);
        left = popover.data('popoverLeft') || (node.offset().left - ((popoverOffsetWidth - node[0].offsetWidth) / 2));
        top = popover.data('popoverTop') || (node.offset().top - popoverOffsetHeight - 7);
        directionFun = popover.data('topFun');
    } else if (direction === 'bottom') {
        popover.find('.arrow').css('left', (popoverClientWidth - 14) / 2);
        left = popover.data('popoverLeft') || (node.offset().left - ((popoverOffsetWidth - node[0].offsetWidth) / 2));
        top = popover.data('popoverTop') || (node.offset().top + node[0].offsetHeight);
        directionFun = popover.data('bottomFun');
    } else if (direction === 'right') {
        popover.find('.arrow').css('top', (popoverClientHeight - 14) / 2);
        left = popover.data('popoverLeft') || (node.offset().left + node[0].offsetWidth);
        top = popover.data('popoverTop') || (node.offset().top - ((popoverOffsetHeight - node[0].offsetHeight) / 2));
        directionFun = popover.data('rightFun');
    } else {
        popover.find('.arrow').css('top', (popoverClientHeight - 14) / 2);
        left = popover.data('popoverLeft') || (node.offset().left - popoverOffsetWidth - 7);
        top = popover.data('popoverTop') || (node.offset().top - ((popoverOffsetHeight - node[0].offsetHeight) / 2));
        directionFun = popover.data('leftFun');
    }
    var animateTime = popover.data('animateTime');
    if (popover.data('firstShow') === true) {
        directionFun && setTimeout(function () {
            directionFun(popover)
        }, parseInt((animateTime || 500) / 2));
        popover.data('firstShow', false);
    } else {
        directionFun && directionFun(popover);
    }
    popover.data('popoverOffsetWidth', popoverOffsetWidth).data('popoverOffsetHeight', popoverOffsetHeight).data('popoverClientHeight', popoverClientHeight).data('popoverClientWidth', popoverClientWidth);
    popover.data('leftOffset') && (left = left + popover.data('leftOffset'));
    popover.data('topOffset') && (top = top + popover.data('topOffset') );
    if (direction === 'top' && top < $('#content').offset().top && turn !== true) {
        adjustPopoverPosition(popover, init, 'bottom', true);
        return;
    } else if (direction === 'bottom' && top + popoverOffsetHeight > $(window).height() && turn !== true) {
        adjustPopoverPosition(popover, init, 'top', true);
        return;
    }
    init && popover.hide();
    popover.css('transform', 'translate3d(' + getEvenNumber(left) + 'px, ' + getEvenNumber(top) + 'px, 0px)');
    if (init) {
        var animate = popover.data('animate');
        if (animate === 'slide') {
            popover.slideDown(animateTime);
        } else if (animate === 'fade') {
            popover.fadeIn(animateTime);
        } else {
            popover.show();
        }
    }
}

function getPopover(node, id) {
    var popoverId = node.data('popoverId_' + (id || 'default'));
    if (popoverId && popoverId !== '') {
        return $('#' + popoverId);
    }
}

function hidePopoverByNode(node, id) {
    var popoverIdMap = node.data('popoverIdMap');
    if (popoverIdMap !== undefined) {
        id = id || 'default';
        var popoverIdArray = popoverIdMap[id];
        if (popoverIdArray && popoverIdArray.length > 0) {
            var oPopoverId = node.data('popoverId_' + id);
            for (var i in popoverIdArray) {
                if (popoverIdArray.hasOwnProperty(i)) {
                    var popoverId = popoverIdArray[i];
                    if (popoverId && popoverId !== '') {
                        if (popoverId === oPopoverId) {
                            hidePopover($('#' + popoverId));
                        } else {
                            hidePopover($('#' + popoverId), true);
                        }
                    }
                }
            }
        }
    }
}

function hideAllPopoverByNode(node) {
    var popoverIdMap = node.data('popoverIdMap');
    if (popoverIdMap !== undefined) {
        for (var key in popoverIdMap) {
            if (popoverIdMap.hasOwnProperty(key)) {
                hidePopoverByNode(node, key);
            }
        }
    }
}

function hidePopover(popover, immediately, hideRemove) {
    if (popover === undefined || popover === null || popover.data('show') !== true) {
        return;
    }
    var preHideFun = popover.data('preHideFun');
    preHideFun && preHideFun();
    var animate = popover.data('animate');
    var animateTime = popover.data('animateTime');
    if (animate === 'slide') {
        popover.slideUp(animateTime);
    } else if (animate === 'fade') {
        popover.fadeOut(animateTime);
    } else {
        popover.hide();
    }
    popover.data('show', false);
    var id = popover.data('id');
    var node = popover.data('node');
    hideRemove = hideRemove || popover.data('hideRemove');
    if (hideRemove === undefined || hideRemove === true) {
        immediately === true ? removePopover(node, popover, id) : node.data('popoverTimeoutId_' + id, setTimeout(function () {
            removePopover(node, popover, id)
        }, 5000));
    }
    var sepLayerId = popover.data('sepLayerId');
    if (sepLayerId && sepLayerId !== '') {
        $('#' + sepLayerId).removeClass('z-index-9998').off('click');
        popover.removeClass('z-index-9999');
        node.removeClass('z-index-9999');
        var fixedTopCover = $('.fixed-top .cover');
        fixedTopCover && fixedTopCover.off('click').hide();
    }
    var hideFun = popover.data('hideFun');
    hideFun && hideFun();
    function removePopover(node, popover, id) {
        var popoverIdMap = node.data('popoverId_' + id, '').data('popoverTimeoutId_' + id, '').data('popoverIdMap');
        if (popoverIdMap !== undefined) {
            var popoverIdArray = popoverIdMap[id];
            popoverIdArray && popoverIdArray.remove(popover.data('popoverId'));
        }
        var sepLayerId = popover.data('sepLayerId');
        if (sepLayerId && sepLayerId !== '') {
            var sepLayer = $('#' + sepLayerId);
            sepLayer && sepLayer.detach();
        }
        popover && popover.detach();
    }
}

function createSlider(options) {
    var sliderId = generateID('slider');
    var container = $('<div id="' + sliderId + '"></div>');
    var sliderTooltip = $('<div class="slider-tooltip"></div>');
    var sliderValue = $('<span class="slider-value"></span>');
    var slider = $('<div class="slider"></div>');
    var sliderRail = $('<div class="slider-rail"></div>');
    var sliderTrack = $('<div class="slider-track"></div>');
    var sliderStep = $('<div class="slider-step"></div>');
    var sliderHandle = $('<div class="slider-handle"></div>');
    var sliderMark = $('<div class="slider-mark"></div>');
    container.append(sliderTooltip.append(sliderValue)).append(slider.append(sliderRail).append(sliderTrack).append(sliderStep).append(sliderHandle).append(sliderMark));
    options.background && sliderRail.css('background', options.background) && sliderTrack.css('background', options.background);
    var minValue = options.min || 0;
    var maxValue = options.max || 100;
    var defaultValue = options.defaultValue || minValue;
    minValue >= maxValue && (minValue = maxValue - 1);
    defaultValue < minValue && (defaultValue = minValue);
    defaultValue > maxValue && (defaultValue = maxValue);
    var gap = 100 / (maxValue - minValue);
    var left = defaultValue === minValue ? 0 : (defaultValue === maxValue ? 100 : (defaultValue - minValue) * gap);
    sliderTrack.css('left', '0%').css('width', left + "%");
    if (options.popover) {
        sliderTooltip.hide();
    } else {
        sliderValue.text(defaultValue + (options.unit || '')).css('left', left + '%');
    }
    var popover, popoverContent = $('<span style="width:20px;text-align:center"></span>'), popoverTimeoutId = -1, popoverOptions = {
        direction: 'top',
        bodyStyle: 'width:30px;height:30px;font-size:14px;padding:5px 5px',
        bodyContent: popoverContent,
        animate: 'fade',
        animateTime: 300
    };
    sliderHandle.css('left', left + '%').on('mousedown', function () {
        popoverTimeoutId !== -1 && clearTimeout(popoverTimeoutId);
        sliderHandle.addClass('selected');
        options.popover && (popover = showPopover(sliderHandle, popoverOptions)) && popoverContent.text((container.data('sliderValue') || defaultValue) + (options.unit || ''));
        $(document).off('mousemove').off('mouseup').on('mousemove', function (event) {
            move(event.clientX);
            options.popover && adjustPopoverPosition(popover);
        }).on('mouseup', function () {
            $(document).off('mousemove').off('mouseup');
            sliderHandle.removeClass('selected');
            (options.popover && hidePopoverByNode(sliderHandle));
        });
    });
    slider.on('mousedown', function (event) {
        if (event.target === sliderHandle[0]) {
            return;
        }
        move(event.clientX);
        if (options.popover) {
            popover = showPopover(sliderHandle, popoverOptions);
            popoverContent.text((container.data('sliderValue') || defaultValue) + (options.unit || ''));
            popoverTimeoutId !== -1 && clearTimeout(popoverTimeoutId);
            popoverTimeoutId = setTimeout(function () {
                hidePopover(popover)
            }, 1500);
        }
    });
    function move(eventLeft) {
        var sliderRailWidth = sliderRail[0].clientWidth;
        var gapWidth = sliderRailWidth / (maxValue - minValue) / 2;
        var offsetLeft = eventLeft - sliderRail.offset().left;
        var value, left;
        if (offsetLeft < gapWidth) {
            value = minValue;
            left = 0;
        } else if (offsetLeft >= sliderRailWidth - gapWidth) {
            value = maxValue;
            left = 100;
        } else {
            value = Math.round(offsetLeft / gapWidth / 2) + minValue;
            left = (value - minValue) * gap;
        }
        sliderHandle.css('left', left + '%');
        sliderTrack.css('width', left + '%');
        var valueWithUnit = value + (options.unit || '');
        if (options.popover) {
            popoverContent.text(valueWithUnit);
        } else {
            sliderValue.text(valueWithUnit).css('left', left + '%');
        }
        container.data('sliderValue', value);
    }

    return container.data('sliderId', sliderId);
}

function getSliderValue(slider) {
    return slider.data('sliderValue');
}

function bindDoubleBoxPopover(node, options) {
    var createDoublebox = function ($this, popover, doubleSelect, options) {
        $this.data('doubleBox') && $this.data('doubleBox').destroy();
        $this.data('doubleBox', doubleSelect.doublebox({
            nonSelectedListLabel: '<span class="translate" translateFor="doubleBox.label.nonSelectedList.' + (options.name || 'default') + '"></span>',
            selectedListLabel: '<span class="translate" translateFor="doubleBox.label.selectedList.' + (options.name || 'default') + '"></span>',
            preserveSelectionOnMove: 'moved',
            moveOnSelect: false,
            doubleMove: true,
            selectorMinimalHeight: 200,
            loading: '<span class="translate" translateFor="doubleBox.loading" style="margin:.5rem 0 0 .7rem"></span>',
            infoText: '{0}/{1} <span class="translate" translateFor="doubleBox.item"></span>',
            infoTextFiltered: '{0}/{1}/{2} <span class="translate" translateFor="doubleBox.item"></span>',
            reload: true,
            reloadFun: function () {
                loadData($this, doubleSelect, options)
            }
        }));
        getPopoverBody(popover).find('.settingUp-btns').append($('<button class="btn btn-default" id="double-box-ok"><span class="translate" translateFor="btn.ok"></span></button>').on('click', function () {
            hidePopover(popover)
        }));
    };
    var loadData = function ($this, doubleSelect, options) {
        if (options.loadUrl) {
            axiosPost({
                url: options.loadUrl,
                success: function (data) {
                    refreshDoublebox($this, doubleSelect, data || []);
                }
            });
        } else {
            refreshDoublebox($this, doubleSelect, options.data || []);
        }
    };
    var refreshDoublebox = function ($this, doubleSelect, tdata) {
        var sValueData = $this.data('allData') || [];
        var tValueData = [];
        if (tdata.length > 0) {
            for (var i in tdata) {
                if (tdata.hasOwnProperty(i)) {
                    var item = tdata[i];
                    var itemValue = item.value;
                    tValueData.push(itemValue);
                    if ($.inArray(itemValue, sValueData) === -1) {
                        doubleSelect.append($("<option id='doublebox_option_" + itemValue + "' value='" + itemValue + "'>" + item.text + "</option>"));
                    }
                }
            }
        }
        if (sValueData.length > 0) {
            for (var j in sValueData) {
                if (sValueData.hasOwnProperty(j)) {
                    var sItemValue = sValueData[j];
                    if ($.inArray(sItemValue, tValueData) === -1) {
                        doubleSelect.find('#doublebox_option_' + sItemValue).remove();
                    }
                }
            }
        }
        $this.data('allData', tValueData);
        $this.data('doubleBox').refresh();
    };
    var getColor = function (index) {
        var colorArray = ['#dc3545', '#ffc107', '#28a745', '#007bff', '#6610f2'];
        return colorArray[index % colorArray.length];
    };
    node.on(options.trigger || 'focus', function () {
        options.fun && options.fun.beforeShow && options.fun.beforeShow();
        var id = 'doubleBox';
        var firstLoad = getPopoverId(node, id) === undefined;
        var newPopover = firstLoad || getPopoverId(node, id) === '';
        var doubleSelectName = 'doubleSelect';
        var doubleSelect = $('<select multiple="multiple" name="' + doubleSelectName + '"></select>');
        node.addClass('focus');
        var popover = showPopover(node, {
            id: id,
            direction: options.direction || 'top',
            animate: 'slide',
            animateTime: 300,
            bodyStyle: 'height:300px;width:600px;font-weight:600;padding:10px 28px 10px 28px',
            bodyContent: doubleSelect,
            hideRemove: false,
            scrollLock: false,
            topFun: function (popover) {
                popover.find('#double-box-ok').addClass('double-box-ok-bottom').removeClass('double-box-ok-top');
            },
            bottomFun: function (popover) {
                popover.find('#double-box-ok').addClass('double-box-ok-top').removeClass('double-box-ok-bottom');
            },
            preHideFun: function () {
                var text = doubleSelect.getSelectedOptionsText(doubleSelectName);
                var value = doubleSelect.getSelectedOptionsValue(doubleSelectName);
                node.removeClass('focus').val(text).data('value', value);
                listenDoubleboxWithCloseBtn(node);
                var textArray = text.split(',');
                if (textArray.length > 1) {
                    var bodyContent = '';
                    var index = 0;
                    for (var i in textArray) {
                        if (textArray.hasOwnProperty(i)) {
                            bodyContent += '<span style="color:' + getColor(index) + '">' + textArray[i] + '</span>';
                            if (textArray.length !== ++index) {
                                bodyContent += '<span style="color:green">,&nbsp;</span>';
                            }
                        }
                    }
                    createTitle(node, {
                        id: 'title',
                        bodyStyle: 'min-height:40px;max-width:600px',
                        bodyContent: bodyContent
                    });
                } else {
                    removeTitle(node);
                }
                options.fun && options.fun.callBack && options.fun.callBack(text, value);
            }
        });
        newPopover && createDoublebox(node, popover, doubleSelect, options);
        firstLoad && loadData(node, doubleSelect, options);
        translate(popover);
    });
}

function createTitle(node, _options) {
    removeTitle(node);
    node.hover(function () {
        var options = $.extend({}, _options);
        for (var i in options) {
            if (options.hasOwnProperty(i)) {
                if (options[i] && typeof options[i] === 'function') {
                    options[i] = options[i]();
                }
            }
        }
        options['allowBodyChange'] = true;
        showPopover(node, options)
    }, function () {
        hidePopoverByNode(node, _options.id)
    });
}

function removeTitle(node, _options) {
    node.unbind('mouseenter').unbind('mouseleave');
    hidePopoverByNode(node, _options && _options.id);
}

function generateID(id) {
    id += '_0xxxxxxx-1xxx-2xxx-3xxx-yxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0;
        var v = c === 'x' ? r : r & 0x3 | 0x8;
        return v.toString(16);
    });
    return id;
}

function createSearchPage(node, options) {
    var widget = $('<div class="widget has-shadow"></div>');
    node.html($('<div class="col-xl-12"></div>').append(widget));
    if (options.createHeader) {
        var header = $('<div class="widget-header bordered no-actions d-flex align-items-center"></div>');
        widget.append(header);
        options.createHeader(header);
    }
    if (options.createContentHeader) {
        var contentHeader = $('<div class="btn-header" style="margin-left:25px"></div>');
        options.createHeader ? contentHeader.css('margin-top', '25px') : widget.css('padding-top', '25px');
        widget.append(contentHeader);
        var batchBtns = $('<span id="batchBtns" class="ml-3"></span>').hide();
        var rightBtns = $('<div style="float:right;margin-right:25px"></div>');
        options.createContentHeader(contentHeader, batchBtns, rightBtns);
        createTitleWithIconBtn(contentHeader.append(batchBtns).append(rightBtns));
    }
    var widgetBody = $('<div class="widget-body"></div>');
    var table = $('<table class="table dataTable table-hover mb-0"></table>');
    var thead = $('<thead></thead>');
    var tbody = $('<tbody></tbody>');
    widget.append(widgetBody.append($('<div class="table-responsive"></div>').append(table.append(thead).append(tbody))));
    if (options.createTableHead) {
        var theadTr = $('<tr></tr>');
        thead.append(theadTr);
        options.createTableHead(theadTr);
        if (options.isCheck !== false) {
            var checkAllId = generateID('check-all');
            theadTr.prepend($('<th style="width:3.2rem;border:0"><div class="styled-checkbox ml-1"><input type="checkbox" name="check-all" id="' + checkAllId + '"><label for="' + checkAllId + '"></label></div></th>'));
            theadTr.find('#' + checkAllId).on('change', function () {
                node.find('input:checkbox[name="checkbox_item"]').prop('checked', $(this).prop("checked") === false);
                node.find('label.click').click();
            });
            tbody.data('checkAllId', checkAllId);
        }
        translate(theadTr);
    }
    if (options.createTableBody) {
        options.createTableBody(tbody);
    }
}

function createTitleWithIconBtn(node) {
    var tem;
    if (node.hasClass('iconBtn')) {
        tem = node;
    } else {
        tem = node.find('.iconBtn');
    }
    tem.each(function () {
        var $this = $(this);
        createTitle($this, {
            bodyContent: function () {
                return $this.attr('popoverTitle')
            }
        });
    });
}

function saveOldParamAndDestroyDataTable(tbody) {
    if (page.dataTable !== undefined && page.dataTable !== null) {
        var dataTable = page.dataTable;
        var dataTableContainer = $(dataTable.table().node()).parent();
        tbody.data('oldPage', dataTable.page());
        tbody.data('searchValue', dataTable.search());
        tbody.data('pageLength', dataTable.page.len());
        tbody.data('scrollLeft', dataTableContainer.scrollLeft());
        dataTableContainer.getNiceScroll().remove();
        dataTable.destroy();
    }
}

function loadOldParamDataTable(tbody) {
    page.dataTable.search(tbody.data('searchValue')).page(tbody.data('oldPage')).page.len(tbody.data('pageLength')).draw(false);
    $(page.dataTable.table().node()).parent().scrollLeft(tbody.data('scrollLeft'));
}

function createSearchTableBody(tbody, options) {
    var checkAllId = tbody.data('checkAllId');
    tbody.find('tr').each(function () {
        var $this = $(this);
        if ($this.find('input[name="checkbox_item"]').length === 0) {
            var id = $this.find('input[name="id"]').val();
            $this.prepend($('<td class="selector"><div class="styled-checkbox ml-1"><input type="checkbox" name="checkbox_item" id="checkbox-' + id + '"><label class="click" id="label-checkbox-' + id + '" for="checkbox-' + id + '"></label></div></td>'));
        }
    });
    translate(tbody);
    tbody.find('input:checkbox[name="checkbox_item"]').on('change', function () {
        var $this = $(this);
        var checked = $this.prop('checked');
        var tr = $this.parents('tr');
        var id = tr.find('input[name="id"]').val();
        var checkedIds = getPageContext('checkedIds');
        if (checked === true) {
            tr.addClass('selected');
            checkedIds.pushWhenNotExist(id);
        } else {
            tr.removeClass('selected');
            checkedIds.remove(id);
        }
        judgeCheckedId(checkedIds);
        var dataTableTbody = $(page.dataTable.table().node()).find('tbody');
        var curPageSelectedCount = dataTableTbody.find('tr.selected').length;
        if (curPageSelectedCount === 0) {
            $('#' + checkAllId).prop('checked', false);
        } else {
            curPageSelectedCount === dataTableTbody.find('tr').length && $('#' + checkAllId).prop('checked', true);
        }
    });
    bindSelector(tbody);
    bindExecuteAction(tbody);
    var checkedIds = getPageContext('checkedIds');
    if (!checkedIds) {
        checkedIds = [];
        pushPageContext('checkedIds', checkedIds);
    }
    if (checkedIds.length > 0) {
        for (var j in checkedIds) {
            if (checkedIds.hasOwnProperty(j)) {
                $('#label-checkbox-' + checkedIds[j]).click();
            }
        }
    }
    var dataTableParams = {
        lengthMenu: [
            [10, 15, 20, -1],
            [10, 15, 20, "All"]
        ],
        order: [1, 'asc'],
        ordering: false,
        bProcessing: true,
        bAutoWidth: false,
        initComplete: function () {
            this.api().columns().every(function () {
                var column = this;
                var columnTh = $(column.header());
                var filter = columnTh.find('.filter');
                if (filter && filter.length > 0) {
                    var filterValue = filter.attr('filterValue') || '';
                    if (filterValue !== '') {
                        var searchValue = getSearchValue(filterValue);
                        column.search(searchValue !== '' ? '^' + searchValue + '$' : '', true, false).draw();
                    }
                    filter.off('click').on('click', function () {
                        var $this = $(this);
                        if ($this.hasClass('filter-menu-show')) {
                            hidePopoverByNode($this);
                            return;
                        }
                        $this.addClass('filter-menu-show');
                        var filterArray = [];
                        var filterValue = $this.attr('filterValue');
                        if (filterValue !== undefined && filterValue !== '') {
                            filterArray = filterValue.split(splitWords);
                        }
                        var popoverBodyContent = $('<div></div>');
                        column.data().unique().sort().each(function (d) {
                            var $span = $(d);
                            if ($span[0].nodeName !== 'SPAN') {
                                $span = $span.find('span');
                            }
                            var translateFor = getTranslateFor($span);
                            var li = $('<li></li>');
                            li.append($('<a href="javascript:void(0);" style="width:100%;padding:.5rem 1rem"><span class="filter-check-mark ' + ($.inArray(translateFor, filterArray) !== -1 ? 'active' : '') + '"></span><span style="display:inline-block">' + getTranslateValueByFor(translateFor) + '</span></a>').on('click', function (e) {
                                e.preventDefault();
                                $this = $(this);
                                var filterValue = filter.attr('filterValue') || '';
                                var filterCount = parseInt(filter.attr('filterCount') || '0');
                                var checkMark = $this.find('.filter-check-mark');
                                if (checkMark.hasClass('active')) {
                                    if (filterValue.indexOf(splitWords + translateFor) > -1) {
                                        filterValue = filterValue.replace(splitWords + translateFor, '');
                                    } else if (filterValue.indexOf(translateFor + splitWords) > -1) {
                                        filterValue = filterValue.replace(translateFor + splitWords, '');
                                    } else {
                                        filterValue = filterValue.replace(translateFor, '');
                                    }
                                    filterCount--;
                                    checkMark.removeClass('active');
                                } else {
                                    if (filterValue !== '') {
                                        filterValue = filterValue + splitWords + translateFor;
                                    } else {
                                        filterValue = translateFor;
                                    }
                                    filterCount++;
                                    checkMark.addClass('active');
                                }
                                if (filterCount !== 0) {
                                    filter.removeClass('active').addClass('active');
                                } else {
                                    filter.removeClass('active');
                                }
                                filter.attr('filterValue', filterValue);
                                filter.attr('filterCount', filterCount + '');
                                var searchValue = getSearchValue(filterValue);
                                column.search(searchValue !== '' ? '^' + searchValue + '$' : '', true, false).draw();
                                adjustPopoverPositionByNode(filter);
                            }));
                            popoverBodyContent.append(li);
                        });
                        showPopover($this, {
                            direction: 'bottom',
                            bodyStyle: 'width:175px;max-height:350px;overflow-y:auto',
                            bodyContent: popoverBodyContent,
                            animate: 'slide',
                            animateTime: 300,
                            niceScroll: true,
                            scrollLock: true,
                            hideFun: function () {
                                filter.removeClass('filter-menu-show');
                            }
                        });
                    });
                }
            });
        },
        drawCallback: function () {
            if (page.dataTable !== undefined) {
                var dataTableTbody = $(page.dataTable.table().node()).find('tbody');
                var selectedTrs = dataTableTbody.find('tr.selected');
                if (selectedTrs.length !== 0) {
                    var checkedIds = getPageContext('checkedIds');
                    if (checkedIds.length === 0) {
                        selectedTrs.find('label.click').click();
                    } else {
                        selectedTrs.each(function () {
                            var selectedTr = $(this);
                            var id = selectedTr.find('input[name="id"]').val();
                            if ($.inArray(id, checkedIds) === -1) {
                                selectedTr.find('label.click').click();
                            }
                        });
                    }
                }
                $('#' + checkAllId).prop('checked', selectedTrs.length === dataTableTbody.find('tr').length);
                resizeContentWithNiceScroll(true);
                textEllipsis();
                dataTableNiceScroll();
            }
        }
    };
    if (options) {
        for (var key in options) {
            if (options.hasOwnProperty(key)) {
                dataTableParams[key] = options[key];
            }
        }
    }
    lang === 'zh' && (dataTableParams['language'] = getTranslateValueByFor('dataTable.language'));
    page.dataTable = tbody.parent().DataTable(dataTableParams);
    textEllipsis();
    dataTableNiceScroll();
}

function judgeCheckedId(checkedIds) {
    checkedIds = checkedIds || getPageContext('checkedIds');
    if (checkedIds.length > 0) {
        $('#batchBtns').show();
        $('#undoSelect').show();
    } else {
        $('#batchBtns').hide();
        $('#undoSelect').hide();
    }
}

function getCheckedId(modalId) {
    return modalId ? getModalContext(modalId, 'checkedIds') : getPageContext('checkedIds');
}

function getSearchValue(filterValue) {
    var filterArray = [];
    if (filterValue !== '') {
        filterArray = filterValue.split(splitWords);
    }
    var searchValue = '';
    for (var p in filterArray) {
        if (filterArray.hasOwnProperty(p)) {
            if (searchValue === '') {
                searchValue = getTranslateValueByFor(filterArray[p]);
            } else {
                searchValue = searchValue + '|' + getTranslateValueByFor(filterArray[p]);
            }
        }
    }
    return searchValue;
}

function pushPageContext(key, value) {
    var pageContext = page['pageContext'];
    if (pageContext === undefined || pageContext === null) {
        pageContext = {};
        page['pageContext'] = pageContext;
    }
    pageContext[key] = value;
}

function getPageContext(key) {
    var pageContext = page['pageContext'];
    if (pageContext !== undefined && pageContext !== null) {
        var value = pageContext[key];
        if (value !== undefined) {
            return value;
        }
    }
    return null;
}

function getPageData() {
    return getPageContext('data');
}

function pushModalContext(modalId, key, value) {
    if (modalId === undefined || modalId === null) {
        alert('未配置modalId!');
        return;
    }
    var pageModalId = 'modal-' + modalId;
    var modalContext = page[pageModalId];
    if (modalContext === undefined || modalContext === null) {
        modalContext = {};
        page[pageModalId] = modalContext;
    }
    modalContext[key] = value;
}

function getModalContext(modalId, key) {
    if (modalId !== undefined && modalId !== null) {
        var modalContext = page['modal-' + modalId];
        if (modalContext !== undefined && modalContext !== null) {
            var value = modalContext[key];
            if (value !== undefined) {
                return value;
            }
        }
    }
    return null;
}

function getModalData(modalId) {
    return getModalContext(modalId, 'data');
}

function setPageTimeout(code, delay) {
    var pageTimeoutId = getPageContext('pageTimeoutId');
    if (pageTimeoutId === null || pageTimeoutId === undefined) {
        pushPageContext('pageTimeoutCode', code);
        pushPageContext('pageTimeoutDelay', delay);
        pushPageContext('pageTimeoutId', setTimeout(function () {
            clearPageTimeoutParam();
            typeof code === "function" ? code() : eval(code);
            pushPageContext('pageTimeoutId', null);
        }, delay));
    }
}

function clearPageTimeout(fun, keepTimeoutParam) {
    var pageTimeoutId = getPageContext('pageTimeoutId');
    if (pageTimeoutId !== undefined && pageTimeoutId !== null) {
        clearTimeout(pageTimeoutId);
        pushPageContext('pageTimeoutId', null);
        fun && fun();
    }
    keepTimeoutParam !== true && clearPageTimeoutParam();
}

function clearPageTimeoutParam() {
    pushPageContext('pageTimeoutCode', null);
    pushPageContext('pageTimeoutDelay', null);
}

function setModalTimeout(modalId, code, delay) {
    var modalTimeoutId = getModalContext(modalId, 'modalTimeoutId');
    if (modalTimeoutId === null || modalTimeoutId === undefined) {
        pushModalContext(modalId, 'modalTimeoutCode', code);
        pushModalContext(modalId, 'modalTimeoutDelay', delay);
        pushModalContext(modalId, 'modalTimeoutId', setTimeout(function () {
            clearModalTimeoutParam(modalId);
            typeof code === "function" ? code() : eval(code);
            pushModalContext(modalId, 'modalTimeoutId', null);
        }, delay));
    }
}

function clearModalTimeout(modalId, fun, keepTimeoutParam) {
    var modalTimeoutId = getModalContext(modalId, 'modalTimeoutId');
    if (modalTimeoutId !== undefined && modalTimeoutId !== null) {
        clearTimeout(modalTimeoutId);
        pushModalContext(modalId, 'modalTimeoutId', null);
        fun && fun();
    }
    keepTimeoutParam !== true && clearModalTimeoutParam(modalId);
}

function clearModalTimeoutParam(modalId) {
    pushModalContext(modalId, 'modalTimeoutCode', null);
    pushModalContext(modalId, 'modalTimeoutDelay', null);
}

function dataTableNiceScroll() {
    var niceScrollWidth = 5;
    if (page.dataTable) {
        var dataTableContainer = $(page.dataTable.table().node()).parent();
        var niceScroll = dataTableContainer.getNiceScroll();
        if (niceScroll.length !== 0) {
            niceScroll.resize();
        } else {
            var dataTableContainerParent = dataTableContainer.parent();
            var dataTableContainerParentPrev = dataTableContainerParent.prev();
            var railhTop = [dataTableContainer[0], dataTableContainerParent.css('margin-top'), dataTableContainerParentPrev[0], dataTableContainerParentPrev.css('margin-top'),
                $('.widget-body').css('padding-top'), $('.widget').css('padding-top'), $('#content').css('padding-top'), (-2 - niceScrollWidth) + 'px'];
            var widgetHeader = $('.widget-header');
            if (widgetHeader.length > 0) {
                railhTop.push(widgetHeader[0]);
            }
            var contentHeader = $('.btn-header');
            if (contentHeader.length > 0) {
                railhTop.push(contentHeader[0]);
                railhTop.push(contentHeader.css('margin-top'));
            }
            dataTableContainer.niceScroll({
                railpadding: {
                    top: 0,
                    right: -2,
                    left: 0,
                    bottom: 0
                },
                scrollspeed: 60,
                zindex: 1,
                cursorborderradius: niceScrollWidth + "px",
                cursorwidth: niceScrollWidth + "px",
                cursorcolor: "rgba(52, 40, 104, 0.2)",
                cursorborder: "rgba(52, 40, 104, 0.2)",
                oneaxismousemode: false,
                railhTop: railhTop
            });
        }
    }
}

function textEllipsis(node, isRemove) {
    var textEllipsis = node ? node.find('.text-ellipsis') : $('.text-ellipsis');
    if (isRemove !== false) {
        removeTextEllipsis(node, textEllipsis);
    }
    textEllipsis.each(function () {
        var $this = $(this);
        if ($this[0].clientHeight > 30) {
            var td = $this.parent();
            $this.css('width', (td[0].clientWidth - 24) + 'px').addClass('text-truncate display-block');
            createTitle(td, {bodyContent: $this.text()});
        }
    });
    var removePopover = node && node.data('removePopover');
    removePopover && $.each(removePopover, function (i, item) {
        setTimeout(function () {
            hidePopover(item, true, true)
        }, 25)
    });
}

function removeTextEllipsis(node, textEllipsisNode) {
    var delay = textEllipsisNode === undefined;
    var removePopover = [];
    textEllipsisNode = textEllipsisNode || (node ? node.find('.text-ellipsis') : $('.text-ellipsis'));
    textEllipsisNode.each(function () {
        if (!delay) {
            removeTitle($(this).removeClass('text-truncate display-block').removeAttr('style').parent())
        } else {
            var popover = getPopover($(this).parent());
            popover && removePopover.push(popover);
        }
    });
    removePopover.length > 0 && node && node.data('removePopover', removePopover);
}

function bindSelector(tbody) {
    tbody.find('.selector').off('mousedown').on('mousedown', function (event) {
        var mousedownTarget = $(event.target);
        var mousedownTr = $(event.target).parents('tr');
        var selectorTable = $(this).parents('table');
        var grabbingTimeoutId = -1;
        var grabTimeoutId = setTimeout(function () {
            selectorTable.addClass('grab');
            grabbingTimeoutId = setTimeout(function () {
                selectorTable.removeClass('grab').addClass('grabbing');
                var tableContainer = selectorTable.parent();
                var scrollLeft = tableContainer.scrollLeft();
                var left = event.clientX;
                $(document).on('mousemove', function (event) {
                    tableContainer.scrollLeft(scrollLeft - event.clientX + left);
                });
            }, 150)
        }, 500);
        $(document).on('mouseup', function (event) {
            $(document).off('mousemove').off('mouseup');
            clearTimeout(grabTimeoutId);
            grabbingTimeoutId !== -1 && clearTimeout(grabbingTimeoutId);
            if (selectorTable.hasClass('grab') || selectorTable.hasClass('grabbing')) {
                selectorTable.removeClass('grab grabbing');
                return;
            }
            var mouseupTarget = $(event.target);
            var mouseupTr = $(event.target).parents('tr');
            if (mousedownTarget.hasClass('click') && mouseupTarget.hasClass('click')) {
                return;
            }
            if (mousedownTr[0] === mouseupTr[0]) {
                mouseupTr.find('label.click').click();
            }
        });
    });
}

function bindExecuteAction(tbody) {
    tbody.find('a').off('click').on('click', function () {
        event.preventDefault();
        event.stopPropagation();
        executeAction($(this));
    }).each(function () {
        var $this = $(this);
        createTitle($this, {
            bodyStyle: 'height:40px', bodyContent: function () {
                return $this.attr('popoverTitle')
            }, leftOffset: -1
        });
    });
    function executeAction(node) {
        var fun = page[node.attr('action')];
        if (typeof fun === 'function') {
            fun.call(this, node);
        }
    }
}

function formPost(url, params) {
    var form = document.createElement("form");
    form.action = url;
    form.method = "post";
    form.style.display = "none";
    for (var x in params) {
        if (params.hasOwnProperty(x)) {
            var opt = document.createElement("textarea");
            opt.name = x;
            opt.value = params[x];
            form.appendChild(opt);
        }
    }
    document.body.appendChild(form);
    form.submit();
    return form;
}

function tologin() {
    window.location.href = contentPath + "/schedule/login";
}

function toIndex() {
    window.location.href = contentPath + "/schedule/index";
}

function ajaxPost(options) {
    $.ajax({
        type: "POST",
        url: contentPath + options.url,
        data: options.data,
        dataType: "json",
        success: options.success,
        error: options.error
    });
}

var schedule_user_name = 'schedule-userName',
    schedule_login_token = 'schedule-loginToken';
function axiosPost(options) {
    var data = '';
    options.data && (data = Qs.stringify(options.data));
    axios.post(contentPath + options.url, data, {
            headers: {
                'user-name': getAttribute(schedule_user_name),
                'login-token': getAttribute(schedule_login_token)
            }
        })
        .then(function (response) {
            var data = response.data;
            if (data.status === 'loginFail') {
                newErrorModal({
                    content: 'modal.' + data.msgCode,
                    hideFun: function () {
                        tologin()
                    }
                });
            } else {
                options.success && options.success(data);
            }
        })
        .catch(function (error) {
            options.error && options.error(error);
        });
}

function setLoginInfo(data) {
    setAttribute(schedule_user_name, data.userName);
    setAttribute(schedule_login_token, data.loginToken);
}

function removeLoginInfo() {
    removeAttribute(schedule_user_name);
    removeAttribute(schedule_login_token);
}

function setAttribute(name, value) {
    if (!window.localStorage) {
        var exp = new Date();
        exp.setTime(exp.getTime() + getsec("1h") * 1);
        document.cookie = name + "=" + value + ";expires=" + exp.toGMTString();
    } else {
        window.localStorage.setItem(name, value);
    }
}

function getAttribute(name) {
    if (!window.localStorage) {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg)) {
            return arr[2];
        }
    } else {
        return window.localStorage.getItem(name);
    }
    return null;
}

function removeAttribute(name) {
    if (!window.localStorage) {
        setAttribute(name, null);
    } else {
        window.localStorage.removeItem(name);
    }
}

function getsec(str) {
    var str1 = parseFloat(str.substring(0, str.length - 1));
    var str2 = str.substring(str.length - 1);
    if (str2 === "s") {
        return str1 * 1000;
    } else if (str2 === "m") {
        return str1 * 60 * 1000;
    } else if (str2 === "h") {
        return str1 * 60 * 60 * 1000;
    } else if (str2 === "d") {
        return str1 * 24 * 60 * 60 * 1000;
    }
}

function load(node, options, loadedFun) {
    var loadExecuteJs = function (executeJs) {
        if (executeJs) {
            if ($.isArray(executeJs)) {
                getScript(executeJs, 0);
            } else {
                $.getScript(contentPath + executeJs, function () {
                    loadedFun && loadedFun()
                });
            }
        } else {
            loadedFun && loadedFun();
        }
    };
    var getScript = function (executeJs, i) {
        $.getScript(contentPath + executeJs[i], function () {
            i + 1 < executeJs.length ? getScript(executeJs, i + 1) : (loadedFun && loadedFun());
        });
    };
    if (options.url) {
        node.load(contentPath + options.url, function () {
            loadExecuteJs(options.executeJs);
        });
    } else {
        loadExecuteJs(options.executeJs);
    }
}

function contentLoad(name, isNewContent, data) {
    var parentMenuItem = getParentMenuItem(name);
    var content = $("#content");
    if (parentMenuItem !== null) {
        if (isNewContent) {
            $('li#' + page.pageId).removeClass("active");
            $('li#' + name).addClass("active");
            if (content.length > 0) {
                clearAllTimeoutAndInterval(true);
                saveScrollParam(content);
                content.data('page', page);
                pageHolder[pageIndex++] = content.detach();
            }
            page = {};
            page.pageId = name;
            checkTabBar();
            data && pushPageContext('data', data);
            content = $('<div class="row" id="content"></div>');
            layout !== 'left' && content.addClass('container m-auto');
            $('#containerFluid').append(content);
            load(content, getMenuItem(parentMenuItem, name), function () {
                page.pageNameArray = getMenuNameArray(parentMenuItem, name);
                showTabBarPageName();
                translate(content);
                resizeContentWithNiceScroll();
                createContentNiceScroll();
            });
        } else {
            page.dataTable = null;
            if (content.length > 0) {
                clearAllTimeoutAndInterval(false);
                load(content, getMenuItem(parentMenuItem, name), function () {
                    translate(content);
                    initNiceScroll(content);
                    resizeContentWithNiceScroll();
                    createContentNiceScroll();
                });
            }
        }
    }
}

function clearAllTimeoutAndInterval(keepTimeoutParam) {
    clearPageTimeout(null, keepTimeoutParam);
    var pageModalIds = page['modalIds'];
    if (pageModalIds && pageModalIds.length > 0) {
        for (var i in pageModalIds) {
            if (pageModalIds.hasOwnProperty(i)) {
                var modalId = pageModalIds[i];
                clearModalTimeout(modalId, null, keepTimeoutParam);
            }
        }
    }
}

function saveScrollParam(content) {
    var pageNiceScroll = content.getNiceScroll(0);
    page['pageScrollX'] = pageNiceScroll.getScrollLeft();
    page['pageScrollY'] = pageNiceScroll.getScrollTop();
}

function loadScrollParam() {
    $('.modal-normal').each(function () {
        var niceScroll = $(this).find('.modal-body').getNiceScroll(0);
        niceScroll.newscrollx && niceScroll.newscrollx !== 0 && niceScroll.setScrollLeft(niceScroll.newscrollx);
        niceScroll.newscrolly && niceScroll.newscrolly !== 0 && niceScroll.setScrollTop(niceScroll.newscrolly);
    });
    resizeModalWithNiceScroll();
    var pageScrollX = page['pageScrollX'];
    var pageScrollY = page['pageScrollY'];
    var pageNiceScroll = $('#content').getNiceScroll(0);
    pageScrollX && pageScrollX !== 0 && pageNiceScroll.setScrollLeft(pageScrollX);
    pageScrollY && pageScrollY !== 0 && pageNiceScroll.setScrollTop(pageScrollY);
}

function resizeModalWithNiceScroll(isDelay) {
    isDelay !== false ? setTimeout(function () {
        resizeModal()
    }, 300) : resizeModal();
}

function resizeModal() {
    $('.modal-normal').each(function () {
        var modalContent = $(this).find('.modal-content');
        !modalContent.data('height') && modalContent.height(($(window).height() - 63) * 0.8 + "px");
        modalContent.find('.modal-body').getNiceScroll(0).resize();
    });
}

function showTabBarPageName() {
    var tabBarHeader = $('<div></div>');
    var pageNameArray = page.pageNameArray;
    for (var i = 0, length = pageNameArray.length; i < length; i++) {
        tabBarHeader.prepend($('<span class="translate" translateFor="menu.' + pageNameArray[i] + '"></span>'));
        i !== length - 1 && tabBarHeader.prepend($('<i class="ion ion-arrow-right-b opacity-6 ml-r-3 mr-r-3"></i>'));
    }
    translate($('#tabBarHeader').html(tabBarHeader));
}

function redirect(name, data) {
    if (name !== page.pageId) {
        destroyOldContent();
        contentLoad(name, true, data);
    }
}

function contentRefresh() {
    destroyOldContent();
    contentLoad(page.pageId, false);
}

function destroyOldContent() {
    $('.popover').each(function () {
        hidePopover($(this), true, true)
    });
    $('.daterangepicker').each(function () {
        $(this).remove()
    });
}

function pageHistory(number) {
    if (pageHolder.hasOwnProperty(pageIndex + number)) {
        var content = $("#content");
        clearAllTimeoutAndInterval(true);
        saveScrollParam(content);
        content.data('page', page);
        pageHolder[pageIndex] = content.detach();
        pageIndex += number;
        checkTabBar();
        $('li#' + page.pageId).removeClass("active");
        page = pageHolder[pageIndex].data('page');
        $('#containerFluid').append(pageHolder[pageIndex]);
        content = $("#content");
        layout === 'left' ? content.removeClass('container m-auto') : content.addClass('container m-auto');
        showTabBarPageName();
        $('li#' + page.pageId).addClass("active");
        resizeContentWithNiceScroll();
        createContentNiceScroll();
        loadScrollParam();
        loadTimeout();
    }
}

function createContentNiceScroll() {
    $('#content').scroll(function () {
        showGoDown();
        showGoTop();
        adjustPosition();
        $('.daterangepicker').each(function () {
            var $this = $(this);
            var daterangepicker = $this.data('daterangepicker');
            if (daterangepicker.isShowing) {
                daterangepicker.move();
                var daterangepickerTop = $this.offset().top;
                daterangepickerTop !== 0 && (daterangepickerTop <= $("#content").offset().top || daterangepickerTop >= $(window).height()) && daterangepicker.element.blur() && daterangepicker.hide();
            }
        });
    }).niceScroll({
        railpadding: {
            top: 0,
            right: 0,
            left: 0,
            bottom: 0
        },
        scrollspeed: 60,
        zindex: 1,
        cursorborderradius: "7px",
        cursorwidth: "7px",
        cursorcolor: "rgba(52, 40, 104, 0.2)",
        cursorborder: "rgba(52, 40, 104, 0.2)"
    });
}

function initNiceScroll(node) {
    var niceScroll = node.getNiceScroll(0);
    if (niceScroll) {
        niceScroll.setScrollLeft(0);
        niceScroll.setScrollTop(0);
    }
}

function loadTimeout() {
    var pageTimeoutCode = getPageContext('pageTimeoutCode');
    var pageTimeoutDelay = getPageContext('pageTimeoutDelay');
    pageTimeoutCode && pageTimeoutDelay && setPageTimeout(pageTimeoutCode, pageTimeoutDelay);
    var pageModalIds = page['modalIds'];
    if (pageModalIds && pageModalIds.length > 0) {
        for (var i in pageModalIds) {
            if (pageModalIds.hasOwnProperty(i)) {
                var modalId = pageModalIds[i];
                var modalTimeoutCode = getModalContext(modalId, 'modalTimeoutCode');
                var modalTimeoutDelay = getModalContext(modalId, 'modalTimeoutDelay');
                modalTimeoutCode && modalTimeoutDelay && setModalTimeout(modalId, modalTimeoutCode, modalTimeoutDelay);
            }
        }
    }
}

function checkTabBar() {
    var tabBarBack = $('#tabBarBack');
    var tabBarForward = $('#tabBarForward');
    if (pageHolder.hasOwnProperty(pageIndex - 1)) {
        tabBarBack.removeClass('disabled');
    } else {
        tabBarBack.addClass('disabled');
    }
    if (pageHolder.hasOwnProperty(pageIndex + 1)) {
        tabBarForward.removeClass('disabled');
    } else {
        tabBarForward.addClass('disabled');
    }
}

function resizeContentWithNiceScroll(cancelShowGoDown) {
    $("#content").css('height', $(window).height() - 119).getNiceScroll().resize();
    cancelShowGoDown !== true && showGoDown() && showGoTop();
}

function showGoDown() {
    var content = $("#content");
    if (content.length > 0) {
        var scrollTop = content.scrollTop();
        var goDown = $('.go-down');
        content[0].scrollHeight - $(window).height() - scrollTop > 210 ? goDown.fadeIn(100) : goDown.fadeOut(200);
    }
    return true;
}

function showGoTop() {
    var content = $("#content");
    if (content.length > 0) {
        var goTop = $('.go-top');
        content.scrollTop() > 360 ? goTop.fadeIn(100) : goTop.fadeOut(200);
    }
    return true;
}

function getEvenNumber(number) {
    number = parseInt(number);
    return number % 2 === 0 ? number : number + 1;
}

Array.prototype.indexOf = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] === val) return i;
    }
    return -1;
};
Array.prototype.pushWhenNotExist = function (val) {
    this.indexOf(val) === -1 && this.push(val);
};
Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

function setCycleValueWithPoint(node, prefix) {
    var times = 1;
    node.data('valueSourceValue', node.val()).data('cycleWithType', 'value').val(prefix + getPoint(times++));
    node.data('valueCycleInterval', setInterval(function () {
        node.val(prefix + getPoint(times++));
    }, 1000));
}

function setCycleTextWithPoint(node, prefix) {
    var times = 1;
    node.data('textSourceValue', node.text()).data('cycleWithType', 'text').text(prefix + getPoint(times++));
    node.data('textCycleInterval', setInterval(function () {
        node.text(prefix + getPoint(times++));
    }, 1000));
}

function removeCycle(node, value) {
    var type = node.data('cycleWithType');
    if (type === 'value') {
        node.val(node.data('valueSourceValue'));
        clearInterval(node.data('valueCycleInterval'));
    } else if (type === 'text') {
        node.text(node.data('textSourceValue'));
        clearInterval(node.data('textCycleInterval'));
    }
}

function getPoint(times) {
    var str = ".";
    for (var i = 0; i < times % 6; i++) {
        str += ".";
    }
    return str;
}

function showErrorNoty(options) {
    options['type'] = 'error';
    options['layout'] = 'center';
    options['animation'] = {open: 'animated fadeInDown', close: 'animated fadeOutUp'};
    newNoty(options);
}

function showSuccessNoty(options) {
    newNoty(options);
}

function newNoty(options) {
    var notyOptions = {
        id: options.id || generateID('noty'),
        type: options.type || 'success',
        layout: options.layout || 'bottomRight',
        progressBar: options.progressBar || true,
        timeout: options.timeout || 2500,
        closeWith: options.closeWith || ['click', 'button'],
        animation: options.animation || {open: 'animated bounceInRight', close: 'animated bounceOutRight'}
    };
    if (options.translateFor && options.translateFor !== '') {
        notyOptions['text'] = '<span class="translate" translateFor="' + options.translateFor + '" translateReplace="' + getTranslateReplace(options.translateReplace) + '" ></span>';
    } else if (options.text) {
        notyOptions['isTranslate'] = false;
        notyOptions['text'] = options.text;
    }
    new Noty(notyOptions).show();
}

function loadInputEmbedCloseBtns(node) {
    node = node ? node.find('input[type="text"]') : $('input[type="text"]');
    node.each(function () {
        var input = $(this);
        if (input.hasClass('datepicker')) {
            input.after($('<button type="button" class="btn btn-secondary input-embed-right-btn"><i class="la la-calendar"></i></button>').on('click', function () {
                input.focus()
            }));
        } else if (input.hasClass('doublebox')) {
            input.after($('<button type="button" class="btn btn-transparent input-embed-right-btn input-embed-close-btn"><i class="ion ion-close-circled"></i></button>').on('click', function () {
                $(this).removeClass('enable').prev().removeClass('pr-r-9').val('');
                input.data('value', '').data('doubleBox') && input.data('doubleBox').elements.removeAllButton.click();
                removeTitle(input);
            }))
        } else if (!input.hasClass('input-readonly')) {
            input.after($('<button type="button" class="btn btn-transparent input-embed-right-btn input-embed-close-btn"><i class="ion ion-close-circled"></i></button>').on('click', function () {
                $(this).removeClass('enable').prev().removeClass('pr-r-9').val('')
            })).on("keyup paste focus", function () {
                input.val() !== '' ? input.addClass('pr-r-9').next().addClass('enable') : input.removeClass('pr-r-9').next().removeClass('enable')
            });
        }
    });
}

function listenDoubleboxWithCloseBtn(input) {
    input.val() !== '' ? input.addClass('pr-r-9').next().addClass('enable') : input.removeClass('pr-r-9').next().removeClass('enable')
}

function hideInputEmbedCloseBtns(node) {
    node = node ? node.find('input[type="text"]') : $('input[type="text"]');
    node.each(function () {
        var input = $(this);
        if (!input.hasClass('datepicker') && !input.hasClass('input-readonly')) {
            input.removeClass('pr-r-9').next().removeClass('enable')
        }
    });
}